<?php

namespace App\V3\V3_1\Models;

use App\V3\V3_1\Models\MaterielContentModel;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MaterielsModel extends Model
{
    use HasFactory;
    protected $table = 'materiel';
    protected $dateFormat = 'U';//这个时间字段被为被格式化为UNIX 时间戳的形式存储

    //toArray 时间转换问题
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    protected $dates = [
        'purchase_time',
        'pay_time',
        'purchase_date'
    ];

    static public function search($data, $userId, $materielIdArr = [])
    {
        $query = MaterielsModel::select(
            'a.id',
            'repeal_status',
            'purchase_time',
            'supplier_name',
            'final_money',
            'out_order_no',
            'purchase_no',
            'pay_status',
            'in_storage_status',
            'username',
            'nickname',
            'purchase_date',
            'preferential_way',
            'shipping_method',
            'transport_type',
            'logistics_company',
            'logistics_order_no',
            'deliver_person',
            'deliver_phone',
            'remark',
        )
            ->from('materiel as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('materielContent', function($query) {
                $query->select(
                    'materiel_content.id',
                    'materiel_id',
                    'unit_price',
                    'num',
                    'rest_num',
                    'a.materiel_name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img',
                    'materiel_content.shelf_id',
                    'materiel_content.location_id',
                    'ss.shelf_name',
                    'l.location_name',
                    'msn.serial_no',
                    's.storage_name',
                    's.storage_address'
                )
                    ->leftJoin('materiel_type as a', 'a.id', '=', 'materiel_content.type_id')
                    ->leftJoin('storage_shelf as ss','materiel_content.shelf_id','=','ss.id')
                    ->leftJoin('storage_shelf_location as l','materiel_content.location_id','=','l.id')
                    ->leftJoin('materiel_serial_number as msn', 'msn.materiel_content_id', '=', 'materiel_content.id')
                    ->leftJoin('storage as s', 'materiel_content.storage_id', '=', 's.id');
            })
            ->where('repeal_status', $data['repeal_status'])
            ->where('a.delete_flag', 0)
            ->where('a.main_id', $userId);

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        if(!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('purchase_time', [$startTime, $endTime]);
        }
        else if(!empty($startTime) && empty($endTime)) {
            $query->where('purchase_time', '>=', $startTime);
        }
        else if(empty($startTime) && !empty($endTime)) {
            $query->where('purchase_time', '<=', $endTime);
        }

        //销售单状态
        switch($data['status']) {
            //新订单
            case 1:
                $query->where('pay_status', 0);
                $query->where('in_storage_status', 0);
                break;
            //已付款(未入库)
            case 2:
                $query->whereIn('pay_status', [1,2]);
                $query->where('in_storage_status', 0);
                break;
            //已完结（已付款，已入库）
            case 3:
                $query->where('pay_status', 2);
                $query->where('in_storage_status', 2);
                break;
            //已入货(未付款)
            case 4:
                $query->where('pay_status', 0);
                $query->whereIn('in_storage_status', [1,2]);
                break;
        }

        if(!empty($materielIdArr)) {
            $query->whereIn('a.id', $materielIdArr);
        }
        else {
            $query->orWhereIn('a.id', $materielIdArr);
        }

        $query = $query->orderBy('id','desc')->get()->toArray();

        return $query;
    }

    static public function content()
    {
        return self::hasMany(MaterielProductContentModel::class, 'product_id', 'id');
    }

    public function materielContent()
    {
        return self::hasMany(MaterielContentModel::class, 'materiel_id', 'id');
    }

    static public function getMaterielId($condition, $userId)
    {
        return self::select(
            'id as materiel_id'
        )
            ->from('materiel as a')
            ->where($condition)
            ->where('main_id', $userId)->get()->toArray();
    }
}
